package cn.jdemo.juc.CompletableFuture.wrapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;

public class WorkerWrapper<T, V> {
    /**
     * 该wrapper的唯一标识
     */
    private String id;
    /**
     * worker将来要处理的param
     */
    private T param;
    private IWorker<T, V> worker;
    private ICallback<T, V> callback;
    private IHandler<T, V> handler;

    private List<WorkerWrapper<?, ?>> nextWrappers = new ArrayList<>();

    /**
     * todo:该map存放所有wrapper的id和wrapper映射
     */
    private Map<String, WorkerWrapper> forParamUseWrappers;

    /**
     * 也是个钩子变量，用来存临时的结果
     */
    private volatile WorkResult<V> workResult = WorkResult.defaultResult();

    public void work(ExecutorService es, Map<String, WorkerWrapper> forParamUseWrappers) {
        this.forParamUseWrappers = forParamUseWrappers;
        this.workerDoJob();
    }

    private WorkResult<V> workerDoJob() {
        handler.begin(param);
        V action = null;
        try{
            action = this.worker.action(param, forParamUseWrappers);
        }catch (Exception ex){
            workResult.setEx(ex);
        }
        workResult.setResultState("success");
        workResult.setResult(action);
        handler.end(param, workResult);
        handler.exception(param, workResult);
        return workResult;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public T getParam() {
        return param;
    }

    public void setParam(T param) {
        this.param = param;
    }

    public IWorker<T, V> getWorker() {
        return worker;
    }

    public void setWorker(IWorker<T, V> worker) {
        this.worker = worker;
    }

    public ICallback<T, V> getCallback() {
        return callback;
    }

    public void setCallback(ICallback<T, V> callback) {
        this.callback = callback;
    }

    public IHandler<T, V> getHandler() {
        return handler;
    }

    public void setHandler(IHandler<T, V> handler) {
        this.handler = handler;
    }
}
